package com.jingbian.cppccbackend.service.impl.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jingbian.cppccbackend.entity.ProposalAttachments;
import com.jingbian.cppccbackend.entity.Proposals;
import com.jingbian.cppccbackend.mapper.admin.adminProposalsMapper;
import com.jingbian.cppccbackend.service.admin.ProposalsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jingbian.cppccbackend.entity.vo.PageVO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;


/**
 * <p>
 * 提案信息表 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-02-11
 */
@Service
public class adminProposalsServiceImpl extends ServiceImpl<adminProposalsMapper, Proposals> implements ProposalsService {

    @Autowired
    private adminProposalsMapper adminProposalsMapper;

    //获取提案详情
    @Override
    public Proposals getProposalById(Integer proposalId) {
        return adminProposalsMapper.getProposalById(proposalId);
    }

    //【管理员】获取提案数据
    @Override
    public PageVO<Proposals> getAllProposalsWithDetails(
            Integer pageNum,
            Integer pageSize,
            String status,
            String proposalType,
            String startDate,
            String endDate,
            String sort,
            String department,
            String searchText,
            Integer pageStatus
    ) {
        PageVO<Proposals> pb = new PageVO<>();
        PageHelper.startPage(pageNum, pageSize);
        List<Proposals> proposals = adminProposalsMapper.getAllProposalsWithDetails(
                status, proposalType, startDate, endDate, sort, department,searchText,pageStatus);
        Page<Proposals> pag = (Page<Proposals>) proposals;
        pb.setTotal(pag.getTotal());
        pb.setItems(pag.getResult());
        return pb;
    }

    //【管理员】更新提案数据状态
    @Override
    public void updateProposalStatus(Integer proposalId, String status, Boolean isOr, Integer pageStatus, String department, String handing_result, List<String> filePaths,String fileName, String size) {
        // 更新提案状态
        adminProposalsMapper.updateProposalStatus(proposalId, status, isOr, pageStatus, department, handing_result);
        
        // 如果是专项处理且有附件，则保存附件信息
        if (pageStatus == 301 ) {
            for (String filePath : filePaths) {
                ProposalAttachments attachment = new ProposalAttachments();
                attachment.setProposalId(proposalId);
                attachment.setFilePath(filePath);
                attachment.setUploadTime(LocalDateTime.now());
                attachment.setFileName(fileName);
                attachment.setSize(size);
                adminProposalsMapper.insertHandlingAttachment(attachment);
            }
        }
    }

    @Override
    public void senBack(Integer proposalId, String status, Boolean isOr, Integer pageStatus, String department) {
        // 更新提案状态
        adminProposalsMapper.sendBack(proposalId, status, isOr, pageStatus, department);
    }

    //【管理员】搜索框查找
    @Override
    public List<Proposals> searchProposals(String searchText) {
        if (StringUtils.isEmpty(searchText)) {
            return adminProposalsMapper.selectList(null);
        }
        return adminProposalsMapper.searchProposals(searchText);
    }

    @Override
    public Map<String, Object> getProposalStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取提案总数
        Integer totalProposals = adminProposalsMapper.getTotalProposals();
        
        // 获取昨日新增提案数
        Integer newProposalsYesterday = adminProposalsMapper.getNewProposalsYesterday();
        
        // 获取已完结提案数
        Integer completedProposals = adminProposalsMapper.getCompletedProposals();
        
        statistics.put("totalProposals", totalProposals);
        statistics.put("newProposalsYesterday", newProposalsYesterday);
        statistics.put("completedProposals", completedProposals);
        
        return statistics;
    }

    @Override
    public List<Map<String, Object>> getProposalTypeDistribution() {
        return adminProposalsMapper.getProposalTypeDistribution();
    }

    @Override
    public List<Map<String, Object>> getProposalTrend(String startDate, String endDate) {
        return adminProposalsMapper.getProposalTrend(startDate, endDate);
    }
    @Override
    public void publicity(Integer proposalId, String status, Boolean isOr) {
        adminProposalsMapper.publicity(proposalId, status, isOr);
    }

    @Override
    public List<Proposals> getProposalsExportList(String status, String proposalType, String startDate, 
                                                String endDate, String sort, String department, 
                                                String searchText, Integer pageStatus) {
        // 直接使用已有的查询方法，但不做分页
        return adminProposalsMapper.getAllProposalsWithDetails(
                status, proposalType, startDate, endDate, sort, department, searchText, pageStatus);
    }
    
    @Override
    public ByteArrayResource generateProposalDoc(Map<String, String> data) {
        ClassPathResource template = new ClassPathResource("templates/proposal.docx");
        XWPFDocument doc = null;
        ByteArrayOutputStream out = null;

        try {
            doc = new XWPFDocument(template.getInputStream());

            // 使用更简单的方法替换文本，不尝试保留复杂样式
            for (XWPFParagraph paragraph : doc.getParagraphs()) {
                replacePlaceholdersInParagraph(paragraph, data);
            }

            // 处理表格中的占位符
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replacePlaceholdersInParagraph(paragraph, data);
                        }
                    }
                }
            }

            out = new ByteArrayOutputStream();
            doc.write(out);
            return new ByteArrayResource(out.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("文档生成失败", e);
        } finally {
            try {
                if (doc != null) doc.close();
                if (out != null) out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 在段落中替换占位符，保留原始样式
     */
    private void replacePlaceholdersInParagraph(XWPFParagraph paragraph, Map<String, String> data) {
        // 检查段落是否包含占位符
        String paragraphText = paragraph.getText();
        boolean containsPlaceholder = false;
        
        for (String key : data.keySet()) {
            if (paragraphText.contains("{{" + key + "}}")) {
                containsPlaceholder = true;
                break;
            }
        }
        
        if (!containsPlaceholder) {
            return;
        }
        
        // 获取所有runs的文本和索引位置信息
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs == null || runs.isEmpty()) {
            return;
        }
        
        // 为每个占位符查找位置并替换
        for (String key : data.keySet()) {
            String placeholder = "{{" + key + "}}";
            String value = data.getOrDefault(key, "");
            
            // 每次替换都需要重新获取runs，因为替换会改变runs的结构
            runs = paragraph.getRuns();
            if (runs == null || runs.isEmpty()) {
                break;
            }
            
            // 查找占位符的位置
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                if (run == null || run.getText(0) == null) {
                    continue;
                }
                
                String text = run.getText(0);
                if (text.contains(placeholder)) {
                    // 直接在当前run中替换占位符
                    run.setText(text.replace(placeholder, value), 0);
                    break;
                } else if (i < runs.size() - 1) {
                    // 检查当前run和下一个run是否包含分割的占位符
                    StringBuilder combined = new StringBuilder(text);
                    int j = i + 1;
                    while (j < runs.size()) {
                        XWPFRun nextRun = runs.get(j);
                        if (nextRun == null || nextRun.getText(0) == null) {
                            j++;
                            continue;
                        }
                        
                        combined.append(nextRun.getText(0));
                        if (combined.toString().contains(placeholder)) {
                            // 找到了跨越多个run的占位符
                            String newText = combined.toString().replace(placeholder, value);
                            
                            // 更新第一个run
                            run.setText(newText, 0);
                            
                            // 清空其他run
                            for (int k = i + 1; k <= j; k++) {
                                if (runs.get(k) != null) {
                                    runs.get(k).setText("", 0);
                                }
                            }
                            break;
                        }
                        j++;
                    }
                }
            }
        }
    }
}